/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 *
 *
 *
 */
package rad.framework.jaxws;

import java.util.List;

import javax.xml.soap.SOAPException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.jboss.seam.Component;
import org.jboss.seam.log.LogProvider;
import org.jboss.seam.log.Logging;

/**
 * This handler processes header field leveraging EL value expressions.
 * 
 * @author boudyacho
 */
public class HeadersHandler extends BaseHandler {

	private static final LogProvider log = Logging
			.getLogProvider(HeadersHandler.class);

	public boolean handleOutbound(SOAPMessageContext smc) {
		try {
			List<HeaderExpression> headers = getHeaderExpressions(smc);
			for (HeaderExpression headerExpression : headers) {
				Object value = headerExpression.getExpression().getValue();
				if (value == null) {
					value = "";
				}
				addHeader(smc, headerExpression.getQName(), value.toString());
			}
			return true;
		} catch (SOAPException ex) {
			log.error("Exception processing outbound message", ex);
			return false;
		}
	}

	public boolean handleInbound(SOAPMessageContext smc) {
		try {
			List<HeaderExpression> headers = getHeaderExpressions(smc);
			for (HeaderExpression headerExpression : headers) {
				String value = getHeaderValue(smc, headerExpression.getQName());
				headerExpression.getExpression().setValue(value);
			}
			return true;
		} catch (SOAPException ex) {
			log.error("Error handling inbound SOAP request", ex);
			return false;
		}
	}

	protected List<HeaderExpression> getHeaderExpressions(MessageContext msgContext) {
		Headers headers = (Headers) Component.getInstance(getHandlerName() + "Headers");
		return headers.getExpressions();
	}
}
